<?php


namespace App\Crontab;


use App\Utils\LogHelp;
use App\Utils\RedisHelp;
use EasySwoole\EasySwoole\Config;
use EasySwoole\EasySwoole\Crontab\AbstractCronTask;
use EasySwoole\EasySwoole\ServerManager;

/**
 * 检验大屏幕通道
 * Class CheckScreenFdCrontab
 * @package App\Crontab
 */
class CheckScreenFdCrontab extends AbstractCronTask
{
    /**
     *   *    *    *    *    *    *
     *   -    -    -    -    -
     *   |    |    |    |    |
     *   |    |    |    |    |
     *   |    |    |    |    +----- day of week (0 - 7) (Sunday=0 or 7)
     *   |    |    |    +---------- month (1 - 12)
     *   |    |    +--------------- day of month (1 - 31)
     *   |    +-------------------- hour (0 - 23)
     *   +------------------------- min (0 - 59)
     *
     * @return string
     */
    public static function getRule():string
    {
        // 每分钟执行一次
        return '* * * * *';
    }

    public static function getTaskName(): string
    {
        // 定时任务的名称
        return 'checkScreenFd';
    }

    public function run(int $taskId, int $workerIndex)
    {
        $server = ServerManager::getInstance()->getSwooleServer();

        $redisHelp = new RedisHelp();
        $redis = $redisHelp->getRedis();

        $websocketFds = $redis->keys('hcrm:screen:fd:*');
        if ($websocketFds) {
            foreach ((array)$websocketFds as $fdKey) {
                $data = explode(':', $fdKey, 4);
                $fd = (int)$data[3];
                $clientInfo = $server->getClientInfo($fd);
                if (empty($clientInfo) || $clientInfo['server_port'] !== Config::getInstance()->getConf("WEBSOCKET_SERVER.PORT")) {
                    // fd信息
                    $screenFdInfo = $redisHelp->getScreenFd($fd);

//                    LogHelp::console('crontab============='.$fd);
                    $redisHelp->delScreenFd($fd);
                    $redisHelp->delScreenProjectFdRem((int)$screenFdInfo['project_id'], $fd);
                }
            }
        }
    }

    public function onException(\Throwable $throwable, int $taskId, int $workerIndex)
    {
        // 捕获run方法内所抛出的异常
        LogHelp::error($throwable->__toString(), 'crontab');
    }
}
